package com.example.controller;

import cn.hutool.json.JSONUtil;
import com.example.common.RpcRequest;
import com.example.common.RpcResponse;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@RestController
@RequestMapping
public class GreetingController implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @PostMapping("/call")
    public RpcResponse call(@RequestBody RpcRequest rpcRequest) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {

        Object service = applicationContext.getBean(rpcRequest.getClassName());

        Object[] param = rpcRequest.getParam();
        Class[] kclss = new Class[param.length];
        for (int i = 0; i < param.length; i++) {
            kclss[i] = param[i].getClass();
        }
        Method method = service.getClass().getMethod(rpcRequest.getMethod(), kclss);
        Object invoke = method.invoke(service, param);

        RpcResponse rpcResponse = new RpcResponse();
        rpcResponse.setData(JSONUtil.toJsonStr(invoke));
        return rpcResponse;
    }

    @GetMapping("/call")
    public String call1(){
        return "{\"id\": 110}";
    }


}
